document.addEventListener("DOMContentLoaded", function () {
    const settingsToggle = document.getElementById("settings-toggle");
    const settingsContent = document.getElementById("settings-content");
    const addressSelect = document.getElementById("address");
    const modelSelect = document.getElementById("model");
    const temperatureInput = document.getElementById("temperature");
    const temperatureValue = document.getElementById("temperature-value");
    const newChatButton = document.getElementById("new-chat");
    const saveChatButton = document.getElementById("save-chat");
    const historyList = document.getElementById("history-list");
    const chatWindow = document.getElementById("chat-window");
    const userInput = document.getElementById("user-input");
    const submitButton = document.getElementById("submit-button");

    const ADDRESSES = {
        "Ollama": {
            "base_url": "http://localhost:11434/v1",
            "models": [ "qwen2.5:3b", "glm4", "llama3.2", "phi", "phi3", "deepseek-r1:1.5b", "mistral:7b-instruct-q2_k"]
        },
        "LMstudio": {
            "base_url": "http://localhost:12345/v1",
            "models": ["qwen2.5-instructv2-7b", "qwen-chatv2-7b", "deepseek-r1-qwen-7b"]
        },
        "AiGitee": {
            "base_url": "https://ai.gitee.com/api/v1",
            "models": [
                "Qwen2-7B-Instruct", "Qwen2.5-72B-Instruct", "Qwen2.5-14B-Instruct", "Qwen2.5-7B-Instruct",
                "Qwen2-72B-Instruct", "Qwen2-7B-Instruct", "Qwen2-32B-Instruct", "QwQ-32B-Preview", "Yi-34B-Chat", "glm-4-9b-chat"
            ]
        },
        "ChatGLM": {
            "base_url": "https://open.bigmodel.cn/api/paas/v4",
            "models": ["glm-4-flash"]
        },
        "THUds": {
            "base_url": "https://madmodel.cs.tsinghua.edu.cn/v1",
            "models": ["DeepSeek-R1-Distill-32B", "DeepSeek-R1-671B"]
        }
    };

    let currentConversation = [];
    let currentConversationTitle = null;
    let chatHistory = [];

    // 初始化设置
    settingsToggle.addEventListener("click", () => {
        settingsContent.classList.toggle("hidden");
    });

    addressSelect.addEventListener("change", () => {
        const selectedAddress = addressSelect.value;
        const models = ADDRESSES[selectedAddress].models;
        modelSelect.innerHTML = models.map(model => `<option value="${model}">${model}</option>`).join("");
    });

    temperatureInput.addEventListener("input", () => {
        temperatureValue.textContent = temperatureInput.value;
    });

    // 初始化模型列表
    addressSelect.dispatchEvent(new Event("change"));
    submitButton.disabled = false;
    userInput.disabled = false;

    // 新建会话
    newChatButton.addEventListener("click", () => {
        if (currentConversation.length > 0) {
            const title = `${currentConversation[1].content.substring(0, 10)} - ${new Date().toLocaleString()}`;
            saveConversation(title, currentConversation);
        }
        currentConversationTitle = null;
        currentConversation = [];
        chatHistory = [];
        submitButton.disabled = false;
        userInput.disabled = false;
        renderChatWindow(); // 清空聊天区
        loadHistory();      // 刷新历史记录
    });

    // 保存对话为 CSV 文件（兼容中文）
    saveChatButton.addEventListener("click", () => {
        if (chatHistory.length === 0) {
            alert("没有可保存的对话内容！");
            return;
        }
        const csvContent = "角色,内容\n" + chatHistory.map(msg => `${msg.role},${msg.content}`).join("\n");
        const blob = new Blob(["\uFEFF" + csvContent], { type: "text/csv;charset=utf-8;" }); // 添加 BOM 头
        const url = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = url;
        a.download = "chat_history.csv";
        a.click();
        URL.revokeObjectURL(url);
    });

    // 加载历史记录
    function loadHistory() {
        const history = JSON.parse(localStorage.getItem("chatHistory") || []);
        historyList.innerHTML = history
            .sort((a, b) => new Date(b.time) - new Date(a.time)) // 按时间逆序排列
            .map(conv => `<li>${conv.title}</li>`)
            .join("");
    }

    // 保存对话到 localStorage
    function saveConversation(title, messages) {
        const history = JSON.parse(localStorage.getItem("chatHistory") || []);
        history.push({ title, time: new Date().toLocaleString(), messages });
        localStorage.setItem("chatHistory", JSON.stringify(history));
        loadHistory();
    }

    // 渲染聊天窗口
    function renderChatWindow() {
        chatWindow.innerHTML = chatHistory.map(msg => `
            <div class="message ${msg.role}">
                ${msg.content}
            </div>
        `).join("");
        // 自动滚动到底部
        chatWindow.scrollTop = chatWindow.scrollHeight;
    }

    // 提交消息逻辑（添加按钮禁用）
    function submitMessage() {
        const userMessage = userInput.value;
        if (!userMessage) return;

        // 禁用按钮和输入框
        submitButton.disabled = true;
        // userInput.disabled = true;

        // ...（原有逻辑）
        currentConversation.push({ role: "user", content: userMessage });
        chatHistory.push({ role: "user", content: userMessage });
        renderChatWindow();

        const payload = {
            model: modelSelect.value,
            messages: currentConversation,
            // stream: true,
            stream:false,
            temperature: parseFloat(temperatureInput.value)
        };

        const headers = {
            "Authorization": `Bearer ${document.getElementById("api-key").value}`,
            "Content-Type": "application/json"
        };

        fetch(`${ADDRESSES[addressSelect.value].base_url}/chat/completions`, {
        // fetch(`${ADDRESSES[addressSelect.value].base_url}/chat/completions`, {
            method: "POST",
            headers: headers,
            body: JSON.stringify(payload)
        })
            .then(response => {
                if (!response.ok) {
                    throw new Error(`API 响应失败! 状态码: ${response.status}`);
                }
                return response.json();
            })
            .then(data => {
                const assistantMessage = data.choices[0].message.content;
                currentConversation.push({ role: "assistant", content: assistantMessage });
                chatHistory.push({ role: "assistant", content: assistantMessage });
                renderChatWindow();
            })
            .catch(error => {
                console.error("请求发送失败:", error);
                alert(`请求发送失败: ${error.message}`);
            })
            .finally(() => {
                // 无论成功与否，重新启用
                submitButton.disabled = false;
                // userInput.disabled = false;
            });

        userInput.value = "";
    }

    // 提交按钮和回车键事件
    submitButton.addEventListener("click", submitMessage);
    userInput.addEventListener("keypress", (e) => {
        if (e.key === "Enter") {
            submitMessage();
        }
    });

    // 初始化加载历史记录
    loadHistory();
});